import axios from 'axios';
import { useRouter } from 'vue-router'
// 创建 Axios 实例
const request = axios.create({
  baseURL: '/api', // 后端 API 的基础 URL
  timeout: 5000, // 请求超时时间
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加用户ID到请求参数
    const userId = localStorage.getItem('userId')
    if (userId) {
      if (config.method === 'get') {
        config.params = { ...config.params, user_id: userId }
      } else {
        config.data = { ...config.data, user_id: userId }
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.request.use(
  config => {
    const router = useRouter()
    const userId = localStorage.getItem('userId')
    if (!userId && (config.url !== '/users/register/' && config.url !== '/users/login/')) {
      router.push('/login')
      return Promise.reject(new Error('请先登录'))
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    console.log('API Response:', response.data)
    return Promise.resolve(response.data || [])
  },
  error => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

export default request; 